<template>
  <div>
    <div style="padding: 10px 0">
      <el-input style="width: 400px" placeholder="请输入名称" clearable size="medium" v-model="name"></el-input>
      <el-button class="ml-5" type="primary" size="medium" @click="load"><i class="el-icon-search"></i> 搜索</el-button>
    </div>
    <!--    <div style="margin: 10px 0">-->
    <!--      &lt;!&ndash;      <el-button type="primary" @click="handleAdd">新增<i&ndash;&gt;-->
    <!--      &lt;!&ndash;          class="el-icon-circle-plus-outline"></i></el-button>&ndash;&gt;-->

    <!--      <el-popconfirm-->
    <!--          class="ml-5"-->
    <!--          confirm-button-text="确定"-->
    <!--          cancel-button-text="我再想想"-->
    <!--          icon="el-icon-info"-->
    <!--          icon-color="red"-->
    <!--          title="您确定删除吗？"-->
    <!--          @confirm="delBatch"-->
    <!--      >-->
    <!--        <el-button type="danger" slot="reference">批量删除<i class="el-icon-remove-outline"></i-->
    <!--        ></el-button>-->
    <!--      </el-popconfirm>-->
    <!--    </div>-->

    <el-table :data="tableData" border stripe size="medium" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <!--      <el-table-column prop="id" label="id" width="80"></el-table-column>-->

      <el-table-column prop="goodsId" label="商品图片">
        <template v-slot="scope">
          <el-image style="width: 100px;height: 100px" :src="scope.row.goodsImg"
                    :preview-src-list="[scope.row.goodsImg]"></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="goodsName" label="商品"></el-table-column>
      <el-table-column prop="price" label="商品价格">
        <template v-slot="scope">
          <span style="color:orangered;">¥ {{ scope.row.price }}</span>
        </template>
      </el-table-column>

      <el-table-column prop="num" label="商品数量">
        <template v-slot="scope">
          <el-input-number v-model="scope.row.num" :min="1" :max="100" label="数量"
                           @change="changeNum(scope.row)"></el-input-number>
        </template>
      </el-table-column>

      <el-table-column prop="time" label="添加时间"></el-table-column>

      <!--      <el-table-column label="购买" width="180" align="center">-->
      <!--        <template v-slot="scope">-->
      <!--          <el-button type="primary" @click="buy(scope.row.id)">购买</el-button>-->
      <!--        </template>-->
      <!--      </el-table-column>-->

      <el-table-column label="操作" width="180" align="center" :header-cell-class-name="'headerBg'"
                       @selection-change="handleCurrentChange">
        <template slot-scope="scope">
          <!--          <el-button type="success" @click="handleEdit(scope.row)"> 编辑<i class="el-icon-edit"></i></el-button>-->

          <el-popconfirm
              class="ml-5"
              confirm-button-text="确定"
              cancel-button-text="我再想想"
              icon="el-icon-info"
              icon-color="red"
              title="您确定删除吗？"
              @confirm="del(scope.row.id)"
          >
            <el-button type="danger" slot="reference">删除<i class="el-icon-remove-outline"></i></el-button>
          </el-popconfirm>

        </template>
      </el-table-column>
    </el-table>

    <div style="padding: 10px 0">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[2, 5, 10, 20]"
          :page-size="pageSize"
          layout="total, prev, pager, next"
          :total="total"
      >
      </el-pagination>
    </div>

    <div style="margin: 10px 0; text-align: right">
      <div style="padding: 10px">当前已选商品总价: <span style="color: orangered">¥ {{ totalPrice }}</span></div>
      <el-button style="color: white;background-color: orangered" size="medium" @click="settleAccount()"><i
          class="el-icon-coin"> 结算</i>
      </el-button>
    </div>
    <el-dialog title="信息" :visible.sync="dialogFormVisible" width="30%">
      <el-form label-width="80px" size="small">
        <el-form-item label="商品id">
          <el-input v-model="form.goodsId" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="用户id">
          <el-input v-model="form.userId" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="商品数量">
          <el-input v-model="form.num" autocomplete="off"></el-input>
        </el-form-item>

        <!--        <el-form-item label="发布时间">-->
        <!--          <el-date-picker v-model="form.time" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"-->
        <!--                          placeholder="选择日期时间"></el-date-picker>-->
        <!--        </el-form-item>-->

        <el-form-item label="封面">
          <el-upload :action="$baseUrl+'/file/upload'" ref="img" :on-success="handleImgUploadSuccess">
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>

export default {
  name: "cart",
  data() {
    return {
      tableData: [],
      pageNum: 1,
      pageSize: 10,
      total: 0,
      name: "",
      form: {},
      multipleSelection: [],
      headerBg: "headerBg",
      dialogFormVisible: false,
      teachers: [],
      user: localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {},
      totalPrice: 0
    };
  },

  created() {
    this.load();
  },

  methods: {
    settleAccount() {
      if (!this.multipleSelection || !this.multipleSelection.length) {
        this.$message.error("请选择要结算的商品")
        return
      }
      console.log(this.multipleSelection)
      let data = {name: this.multipleSelection[0].goodsName, totalPrice: this.totalPrice, carts: this.multipleSelection}
      console.log(data)
      this.request.post("/ordersPlus", data).then(res => {
        if (res.code === "200") {
          this.$message.success("结算成功");
          this.load();
        } else {
          this.$message.error(res.msg);
        }
      })
    },

    changeNum(row) {
      console.log('row', row)
      this.request.post("/cart/num/" + row.id + "/" + row.num).then(res => {

        //  计算总价格
        this.totalPrice = 0
        this.multipleSelection.forEach(item => {
          item.num = row.num  // 更新选中的数组数量
          this.totalPrice += item.price * row.num  //这个地方小坑因为我们的数字发生变化了，需受取到最新的值,进行计算
        })
        this.totalPrice = this.totalPrice.toFixed(2)
      });
    },

    save() {
      console.log('this.form', this.form)
      this.request.post("/cart", this.form).then((res) => {
        if (res.code === '200') {
          this.$message.success("保存成功");
          this.dialogFormVisible = false;
          this.load();
        } else {
          this.$message.error("保存失败");
        }
      });
    },

    load() {
      //加载2条数据
      this.request.get("/cart/page", {
        params: {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          name: this.name,
        },
      }).then((res) => {
        console.log(res);
        this.tableData = res.data.records;
        this.total = res.data.total;
      });
    },


    del(id) {
      this.request.delete("/cart/" + id).then((res) => {
        if (res.code === "200") {
          this.$message.success("删除成功");
          this.load();
        } else {
          this.$message.error("删除失败");
        }
      });
    },
    handleSelectionChange(val) {
      console.log('val', val)
      this.totalPrice = 0
      this.multipleSelection = val;
      //  进行计算操作
      if (val && val.length) {
        val.forEach(item => {
          this.totalPrice += item.num * item.price
        })
        this.totalPrice = this.totalPrice.toFixed(2)
      }
    },

    delBatch() {
      if (!this.multipleSelection.length) {
        this.$message.error("请选择要删除的数据")
        return
      }
      let ids = this.multipleSelection.map((v) => v.id); //[{},{},{}] => [1,2,3]
      console.log(ids);
      this.request.post("/cart/del/batch/", ids).then((res) => {
        if (res.code === "200") {
          this.$message.success("批量删除成功");
          this.load();
        } else {
          this.$message.error("删除失败");
        }
      });
    },
    handleAdd() {
      this.dialogFormVisible = true;
      this.form = {};
    },
    //重置
    reset() {
      this.name = "";
      this.load();
    },
    handleEdit(row) {
      console.log("row=", row);
      this.form = row;
      this.dialogFormVisible = true;
    },
    handleSizeChange(pageSize) {
      console.log(pageSize);
      this.pageSize = pageSize;
      this.load();
    },
    handleCurrentChange(pageNum) {
      console.log(pageNum);
      this.pageNum = pageNum;
      this.load();
    },
    //上传文件
    handleImgUploadSuccess(res) {
      this.form.img = res
      console.log(res);
      this.load();
    },

    // 下载
    download(url) {
      window.open(url);
    },
  },
};
</script>

<style scoped>
.headerBg {
  background-color: #eee !important;
}
</style>